import {useEffect, useLayoutEffect, useState} from 'react';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/line';
import 'echarts/theme/macarons';
import styles from './index.module.scss';
import React from 'react';
import {Card} from 'antd';

/**
 * 折线图
 */
const KeyChart: React.FC<{ dbSize: number, time: string }> = props => {

  // 图表参数
  const {dbSize, time} = props

  let lineChartRef: HTMLDivElement;

  const [timeData, setTimeData] = useState<string[]>([])
  const [dbSizeData, setDbSizeData] = useState<number[]>([])
  const [lineChart, setLineChart] = useState<any>()

  const config: Record<string, any> = {
    xAxis: {
      data: [],
      boundaryGap: false,
      axisTick: {
        show: false
      }
    },
    grid: {
      left: 0,
      right: 20,
      bottom: 0,
      top: 30,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      padding: [5, 10]
    },
    yAxis: {
      axisTick: {
        show: false
      }
    },
    legend: {},
    series: [{
      name: 'key数量',
      itemStyle: {
        normal: {
          color: '#FF005A',
          lineStyle: {
            color: '#FF005A',
            width: 2
          },
        },

      },
      smooth: true,
      type: 'line',
      data: [],
      animationDuration: 2000,
      animationEasing: 'cubicInOut',
    }]
  }

  useEffect(() => {
    // 获取echarts实例
    const instance: any = echarts.init(lineChartRef, "macarons")
    instance.showLoading()
    // 设置参数
    setEcharts(instance)
    // 开启自适应
    window.addEventListener('resize', instance.resize)
    // 设置到state
    setLineChart(instance)
    return () => {
      window.removeEventListener('resize', instance.resize)
    }
  }, [])

  // 依赖props更新
  useEffect(() => {
    if (!lineChart) {
      return
    }
    setEcharts(lineChart)
    lineChart.resize()
  }, [props])

  // 设置echarts属性
  const setEcharts = (instance: any | undefined = undefined) => {
    if (!dbSize) {
      return
    }

    const ctr = instance || lineChart
    if (!ctr) return

    // 时间
    if (timeData.length >= 6) {
      timeData.shift();
    }
    const timeTemp = [...timeData, time]
    // config.xAxis.data.push(...timeTemp)
    config.xAxis.data.push(...['16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'])
    // setTimeData(timeTemp)

    // 分配内存
    if (dbSizeData.length >= 6) {
      dbSizeData.shift();
    }

    const dbSizeTemp = [...dbSizeData, dbSize]
    // config.series[0].data.push(...dbSizeTemp)
    config.series[0].data.push(...[0.2, 0.4, 0.6, 7, 4, 2, 4, 6])
    // setDbSizeData(dbSizeTemp)

    // 设置数据
    ctr.setOption(config)
    ctr.hideLoading()
  }

  return (
    <Card title="key数量" style={{margin: '0 20px 20px 0'}}>
      <div
        ref={(ref: HTMLDivElement) => {
          lineChartRef = ref
        }}
        className={styles.lineChart}
      >
      </div>
    </Card>
  )
}

export default KeyChart
